//
//  NSString+Category.m
//  YLCloudCast
//
//  Created by Zoo on 2017/4/24.
//  Copyright © 2017年 Zoo. All rights reserved.
//

#import "NSString+Category.h"
#import <objc/runtime.h>
#import <CommonCrypto/CommonCrypto.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

@implementation NSString (Category)

- (NSString *)formatPhoneNumber {
    NSMutableString * msTmp = [NSMutableString stringWithString:self];
    [msTmp insertString:@"-" atIndex:3];
    [msTmp insertString:@"-" atIndex:7];
    return [msTmp copy];
}

- (BOOL)isValidateMobile {
    //手机号以13，15，18, 17, 开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(17[0-9])|(147)|(15[^4,\\D])|(18[0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

- (BOOL)isValidateEmail {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

- (BOOL)isValidatePassword {
    NSString *passRegex = /*@"(?!^\\d+$)(?!^[a-zA-Z]+$)(?!^[_#@]+$).*/@".{1,10}";
    NSPredicate *passTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passRegex];
    return [passTest evaluateWithObject:self];
}

- (BOOL)isValidateMoney {
    NSRange range = [self rangeOfString:@"."];
    NSString * regex = range.location==0?@"^(\\.[0-9]{1,2})?$":@"^[0-9]+(\\.[0-9]{1,2})?$";
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:self];
}

+ (void)printMethodsOfClass:(Class)className {
#if DEBUG
    unsigned int outCount = 0;
    Method * methods = class_copyMethodList(className, &outCount);
    for (unsigned int i = 0; i < outCount; i++) {
        Method method = methods[i];
        const char * name = sel_getName(method_getName(method));
        const char * type = method_copyReturnType(method);
        YLLog(@"方法类型为 %s 的 %s", type, name);
    }
    free(methods);
#endif
}

+ (void)printPropertyOfClass:(Class)className {
#if DEBUG
    unsigned int outCount = 0;
    Ivar * ivars = class_copyIvarList(className, &outCount);
    for (unsigned int i = 0; i < outCount; i ++) {
        Ivar ivar = ivars[i];
        const char * name = ivar_getName(ivar);
        const char * type = ivar_getTypeEncoding(ivar);
        YLLog(@"类型为 %s 的 %s ", type, name);
    }
    free(ivars);
#endif
}

+ (void)printFileAttributes:(NSString *)path {
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSDictionary<NSFileAttributeKey,id> * attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
        YLLog(@"%@", path);
        [attributes enumerateKeysAndObjectsUsingBlock:^(NSFileAttributeKey  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            YLLog(@"%@:%@", key, obj);
        }];
    }
}

- (NSString *)md5Encrypt {
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];
    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02x",result[i]];
    }
    return ret;
}

- (NSString*)replaceNewlineAndSpace {
    NSMutableString * msTmp = [NSMutableString string];
    for (NSInteger i = 0; i < self.length; i++) {
        NSString * sub = [self substringWithRange:NSMakeRange(i, 1)];
        if ([@[@"\n",@"\r",@" ",@" ",@"-",@"(",@")"] containsObject:sub]) {
            continue;
        } else {
            [msTmp appendString:sub];
        }
    }
    return [msTmp copy];
}

- (NSString *)phoneNumberMakeClean {
    __block NSString * sTmp = [self replaceNewlineAndSpace];
    if ([sTmp isValidateMobile]==NO) {
        NSArray<NSString*> * aTmp = @[@"86",@"17951",@"+86",];
        [aTmp enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSRange range = [sTmp rangeOfString:obj];
            if (range.location == 0) {
                sTmp = [sTmp stringByReplacingOccurrencesOfString:obj withString:@""];
            }
        }];
    }
    return sTmp;
}

+ (NSString*)makeFileToDisplay:(CGFloat)size {
    NSString * sTmp = @"", * suffix = @"K";
    if (size>1024) {
        size/=1024.0f;
        suffix = @"M";
    }
    if (size>1024) {
        size/=1024.0f;
        suffix = @"G";
    }
    if (size>1024) {
        size/=1024.0f;
        suffix = @"T";
    }
    sTmp = [NSString stringWithFormat:@"%@%@", [[self class] makeNumberDoubleShort:size], suffix];
    return sTmp;
}

+ (NSString*)makeNumberDoubleShort:(CGFloat)number {
    NSString * suffix = @"", * sTmp = nil;
    
    if (number >= 10000 && number < 10000000) {
        suffix = @"万";
        number/=10000.0f;
    } else if (number >= 10000000 && number < 100000000) {
        suffix = @"千万";
        number/=10000000.0f;
    } else if (number >= 100000000) {
        suffix = @"亿";
        number/=100000000.0f;
    }
    sTmp = [NSString stringWithFormat:@"%.2f%@", number, suffix];
    return sTmp;
}

- (BOOL)isChinese {
    for(int i=0; i< [self length];i++) {
        int a = [self characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff) return YES;
    }
    return NO;
}

+ (NSString *)localIp {
    NSString *address = @"";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    YLLog(@"-------ip %@", address);
    return address;
}

+ (NSString*)platform {
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    
    if ([@[@"iPhone3,1",@"iPhone3,2",@"iPhone3,3"] containsObject:platform])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    
    if ([@[@"iPhone5,1",@"iPhone5,2"] containsObject:platform]) return @"iPhone 5";
    if ([@[@"iPhone5,3",@"iPhone5,4"] containsObject:platform]) return @"iPhone 5c";
    if ([@[@"iPhone6,1",@"iPhone6,2"] containsObject:platform]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    
    if ([platform isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    
    if ([platform isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    
    if ([@[@"iPhone9,1",@"iPhone9,3"] containsObject:platform]) return @"iPhone 7";
    if ([@[@"iPhone9,2",@"iPhone9,4"] containsObject:platform]) return @"iPhone 7 Plus";
    
    if ([@[@"iPhone10,1",@"iPhone10,4"] containsObject:platform])   return @"iPhone 8";
    if ([@[@"iPhone10,2",@"iPhone10,5"] containsObject:platform])   return @"iPhone 8 Plus";
    
    if ([@[@"iPhone10,3",@"iPhone10,6"] containsObject:platform])   return @"iPhone X";
    
    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch 1";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch 2";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch 3";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch 4";
    if ([platform isEqualToString:@"iPod5,1"])      return @"iPod Touch 5";
    if ([platform isEqualToString:@"iPod7,1"])      return @"iPod Touch 6";
    
    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([platform isEqualToString:@"iPad1,2"])      return @"iPad 3G";
    if ([@[@"iPad2,1",@"iPad2,2",@"iPad2,3",@"iPad2,4"] containsObject:platform])   return @"iPad 2";
    
    if ([@[@"iPad2,5",@"iPad2,6",@"iPad2,7",] containsObject:platform])             return @"iPad Mini";
    if ([@[@"iPad4,5",@"iPad4,6",@"iPad4,4",] containsObject:platform])             return @"iPad Mini 2";
    if ([@[@"iPad4,7",@"iPad4,8",@"iPad4,9",] containsObject:platform])             return @"iPad Mini 3";
    if ([@[@"iPad5,1",@"iPad5,2",] containsObject:platform])                        return @"iPad Mini 4";
    
    if ([@[@"iPad3,1",@"iPad3,2",@"iPad3,3",] containsObject:platform])             return @"iPad 3";
    if ([@[@"iPad3,4",@"iPad3,5",@"iPad3,6",] containsObject:platform])             return @"iPad 4";
    if ([@[@"iPad6,11",@"iPad6,12",] containsObject:platform])                      return @"iPad 5";
    
    if ([@[@"iPad4,1",@"iPad4,2",] containsObject:platform])                        return @"iPad Air";
    if ([@[@"iPad5,3",@"iPad5,4",] containsObject:platform])                        return @"iPad Air 2";
    
    if ([@[@"iPad6,3",@"iPad6,4",@"iPad6,7",@"iPad6,8",] containsObject:platform])  return @"iPad Pro";
    if ([@[@"iPad7,1",@"iPad7,2",@"iPad7,3",@"iPad7,4"] containsObject:platform])   return @"iPad Pro 2";
    
    if ([platform isEqualToString:@"i386"])         return @"Mac 32bit";
    if ([platform isEqualToString:@"x86_64"])       return @"Mac 64bit";
    
    return [[UIDevice currentDevice] model];
}

- (NSString *)formatMeetingId {
    NSMutableString * mStr = [NSMutableString stringWithString:self];
    for (NSUInteger i = 0; i < self.length; i++) {
        if (i==3 || i==7) {
            [mStr insertString:@"-" atIndex:i];
        }
    }
    return [mStr copy];
}

- (BOOL)isValidateBankCard {
    
    if (!self.length) return NO;
    
    int oddSum = 0;     // 奇数和
    int evenSum = 0;    // 偶数和
    int allSum = 0;     // 总和
    
    // 循环加和
    for (NSInteger i = 1; i <= self.length; i++) {
        NSString *theNumber = [self substringWithRange:NSMakeRange(self.length-i, 1)];
        int lastNumber = [theNumber intValue];
        if (i%2 == 0) {
            // 偶数位
            lastNumber *= 2;
            if (lastNumber > 9) {
                lastNumber -=9;
            }
            evenSum += lastNumber;
        } else {
            // 奇数位
            oddSum += lastNumber;
        }
    }
    allSum = oddSum + evenSum;
    // 是否合法
    if (allSum%10 == 0) {
        return YES;
    } else {
        return NO;
    }
}

@end













































